//
//  NSDate+Extension.swift
//  WeiDo
//
//  Created by XISHAN on 16/3/10.
//  Copyright © 2016年 XISHAN. All rights reserved.
//

import UIKit

extension NSDate{
    
    //"created_at": "Tue May 31 17:46:55 +0800 2011",
    
    class func originalDateWithString(dateString:String?) -> (NSDate?) {
        guard let s = dateString else {
            
            return nil
        }
        
        let fm = NSDateFormatter()
        fm.dateFormat = "EEE MM dd HH:mm:ss z yyyy"
        fm.locale = NSLocale(localeIdentifier: "en")
        return fm.dateFromString(s)
    }
    
    var dateDescription :String?{
        
        let fm = NSDateFormatter()
        fm.locale = NSLocale(localeIdentifier: "en")

        let calender = NSCalendar.currentCalendar()

        
        if isDateInThisYear(self){
            //今年
            
            if calender.isDateInToday(self){
                
                //今天
                let result = -self.timeIntervalSinceNow
                if result < 60 {
                    return "刚刚"
                }else if result < 3600{
                    return "\(Int(result/60))分钟之前"
                }else {
                    return "\(Int(result/3600))小时之前"
                }
                
            }
            else if calender.isDateInYesterday(self){
                //昨天
                fm.dateFormat = "昨天 HH:mm"
                return fm.stringFromDate(self)
            }else {
                //这个月
                fm.dateFormat = "MM-dd HH:mm"
                return fm.stringFromDate(self)
            }
            
        }
        else{
            //不是今年
            fm.dateFormat = "yyyy-MM-dd"
            return fm.stringFromDate(self)
        }
        
        
        
        
    }
    
    
    //判断是不是今年
    func isDateInThisYear(targetDate:NSDate) -> Bool{
        
        let currentDate = NSDate()
        let fm = NSDateFormatter()
        
        fm.dateFormat = "yyyy"
        fm.locale = NSLocale(localeIdentifier: "en")
        
        let currentDateYearStr = fm.stringFromDate(currentDate)
        let targetDateYearStr = fm.stringFromDate(targetDate)
        
        return currentDateYearStr == targetDateYearStr
        
    }
    
    
    
}
